package com.car.account.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.car.account.entity.PlatformPermission;
import com.car.account.entity.PlatformResource;
import com.car.account.entity.PlatformRole;
import com.car.account.mapper.PlatformPermissionMapper;
import com.car.account.mapper.PlatformRoleMapper;
import com.car.account.service.PlatformResourceService;
import com.car.account.service.PlatformRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@Service
public class PlatformRoleServiceImpl extends ServiceImpl<PlatformRoleMapper, PlatformRole> implements PlatformRoleService {

    @Resource
    private PlatformPermissionMapper platformPermissionMapper;

    @Resource
    private PlatformResourceService platformResourceService;

    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) throws Exception {
// 先删除当前角色id所有的绑定关系
        platformPermissionMapper.deleteByRoleId(roleId);

        // 再把前端传过来的菜单id数组绑定到当前的这个角色id上去
        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            PlatformResource menu = platformResourceService.getById(menuId);
            if (menu.getParentId() != 0 && !menuIdsCopy.contains(menu.getParentId())) { // 二级菜单 并且传过来的menuId数组里面没有它的父级id
                // 那么我们就得补上这个父级id
                PlatformPermission roleMenu = new PlatformPermission();
                roleMenu.setRole(roleId);
                roleMenu.setResourceId(menu.getParentId());
                platformPermissionMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getParentId());
            }
            PlatformPermission roleMenu = new PlatformPermission();
            roleMenu.setRole(roleId);
            roleMenu.setResourceId(menuId);
            platformPermissionMapper.insert(roleMenu);
        }
    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) throws Exception {
        return platformPermissionMapper.selectByRoleId(roleId);
    }
}
